from rest_framework import viewsets, status, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q
from django.core.paginator import Paginator
from .response import APIResponse, api_exception_handler
from .permissions import HasPermission
from .pagination import StandardResultsSetPagination
import logging

logger = logging.getLogger(__name__)


class BaseModelViewSet(viewsets.ModelViewSet):
    """基础模型ViewSet，提供通用的CRUD操作"""
    
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    pagination_class = StandardResultsSetPagination
    
    # 子类需要定义的属性
    queryset = None
    serializer_class = None
    search_fields = []
    filterset_fields = []
    ordering_fields = []
    ordering = ['-created_at']
    
    # 权限相关
    required_permissions = {
        'list': None,
        'retrieve': None,
        'create': None,
        'update': None,
        'destroy': None,
    }

    def get_permissions(self):
        """根据动作获取权限"""
        permissions = [IsAuthenticated()]
        
        action_permission = self.required_permissions.get(self.action)
        if action_permission:
            permissions.append(HasPermission(action_permission))
        
        return permissions

    @api_exception_handler
    def list(self, request, *args, **kwargs):
        """列表查询"""
        queryset = self.filter_queryset(self.get_queryset())
        
        # 自定义搜索逻辑
        search = request.query_params.get('search', '')
        if search and self.search_fields:
            search_q = Q()
            for field in self.search_fields:
                search_q |= Q(**{f"{field}__icontains": search})
            queryset = queryset.filter(search_q)
        
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return APIResponse.success(serializer.data)

    @api_exception_handler
    def create(self, request, *args, **kwargs):
        """创建对象"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 添加创建者信息
        if hasattr(serializer.Meta.model, 'created_by'):
            serializer.save(created_by=request.user)
        else:
            serializer.save()
        
        return APIResponse.success(
            serializer.data, 
            message="创建成功", 
            status_code=status.HTTP_201_CREATED
        )

    @api_exception_handler
    def retrieve(self, request, *args, **kwargs):
        """获取单个对象"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return APIResponse.success(serializer.data)

    @api_exception_handler
    def update(self, request, *args, **kwargs):
        """更新对象"""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        
        # 添加更新者信息
        if hasattr(instance, 'updated_by'):
            serializer.save(updated_by=request.user)
        else:
            serializer.save()

        return APIResponse.success(serializer.data, message="更新成功")

    @api_exception_handler
    def destroy(self, request, *args, **kwargs):
        """删除对象"""
        instance = self.get_object()
        
        # 软删除支持
        if hasattr(instance, 'is_deleted'):
            instance.is_deleted = True
            instance.save()
        else:
            instance.delete()
        
        return APIResponse.success(message="删除成功")

    @api_exception_handler
    @action(detail=False, methods=['post'])
    def batch_delete(self, request):
        """批量删除"""
        ids = request.data.get('ids', [])
        if not ids:
            return APIResponse.error("请提供要删除的ID列表")
        
        queryset = self.get_queryset().filter(id__in=ids)
        count = queryset.count()
        
        # 软删除支持
        if hasattr(self.queryset.model, 'is_deleted'):
            queryset.update(is_deleted=True)
        else:
            queryset.delete()
        
        return APIResponse.success(message=f"成功删除 {count} 个项目")

    @action(detail=False, methods=['get'])
    @api_exception_handler
    def export(self, request):
        """导出数据"""
        # 这里可以实现数据导出逻辑
        return APIResponse.error("导出功能开发中", status_code=status.HTTP_501_NOT_IMPLEMENTED)

    def get_queryset(self):
        """获取查询集，支持软删除过滤"""
        queryset = super().get_queryset()
        
        # 过滤软删除的记录
        if hasattr(self.queryset.model, 'is_deleted'):
            queryset = queryset.filter(is_deleted=False)
        
        return queryset


class ReadOnlyModelViewSet(viewsets.ReadOnlyModelViewSet):
    """只读模型ViewSet"""
    
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    pagination_class = StandardResultsSetPagination
    
    @api_exception_handler
    def list(self, request, *args, **kwargs):
        """列表查询"""
        queryset = self.filter_queryset(self.get_queryset())
        
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return APIResponse.success(serializer.data)

    @api_exception_handler
    def retrieve(self, request, *args, **kwargs):
        """获取单个对象"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return APIResponse.success(serializer.data)


class MonitoringViewSet(viewsets.ViewSet):
    """监控相关ViewSet基类"""
    
    permission_classes = [IsAuthenticated]
    
    @api_exception_handler
    def get_metrics(self, request, metric_type):
        """获取指标数据的通用方法"""
        from .monitoring import PerformanceMonitor
        
        method_name = f"get_{metric_type}_metrics"
        if hasattr(PerformanceMonitor, method_name):
            metrics = getattr(PerformanceMonitor, method_name)()
            if metrics:
                return APIResponse.success(metrics)
            else:
                return APIResponse.error(f"无法获取{metric_type}指标")
        else:
            return APIResponse.error(f"不支持的指标类型: {metric_type}")
